<template>
  <div class="task-scenarios-container">
    <el-card class="mb-4">
      <template #header>
        <div class="card-header">
          <span>任务场景管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="showCreateDialog" icon="Plus">
              新建场景
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 搜索筛选 -->
      <div class="search-filter">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
              v-model="searchForm.name"
              placeholder="场景名称搜索"
              prefix-icon="Search"
              clearable
              @keyup.enter.native="handleSearch"
            />
          </el-col>
          <el-col :span="6">
            <el-select
              v-model="searchForm.scenario_type"
              placeholder="场景类型"
              clearable
            >
              <el-option label="预设模板" value="preset"></el-option>
              <el-option label="自定义场景" value="custom"></el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-select
              v-model="searchForm.is_active"
              placeholder="状态"
              clearable
            >
              <el-option label="启用" :value="true"></el-option>
              <el-option label="禁用" :value="false"></el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 预设模板卡片 -->
    <el-card v-if="presetTemplates.length > 0" class="mb-4">
      <template #header>
        <div class="card-header">
          <span>预设场景模板</span>
          <el-text type="info" size="small">点击模板卡片可查看详情</el-text>
        </div>
      </template>
      
      <div class="template-cards">
        <el-card
          v-for="template in presetTemplates"
          :key="template.id"
          class="template-card"
          shadow="hover"
          @click="viewTemplateDetail(template)"
        >
          <div class="template-content">
            <div class="template-header">
              <h3 class="template-title">{{ template.name }}</h3>
              <el-tag type="info" size="small">预设模板</el-tag>
            </div>
            <p class="template-desc">{{ template.description }}</p>
            <div class="template-tags">
              <el-tag size="small" v-for="(target, index) in processDetectionTargets(template.detection_targets || template.detection_target_objects).slice(0, 3)" :key="index">
                {{ target }}
              </el-tag>
              <el-tag size="small" type="info" v-if="processDetectionTargets(template.detection_targets || template.detection_target_objects).length > 3">
                +{{ processDetectionTargets(template.detection_targets || template.detection_target_objects).length - 3 }}
              </el-tag>
            </div>
            <div class="template-drone-types" v-if="template.drone_type_requirements && template.drone_type_requirements.length > 0">
              <el-tag size="small" type="primary" v-for="(type, index) in processDroneTypes(template.drone_type_requirements).slice(0, 3)" :key="index" class="mr-1">
                {{ type }}
              </el-tag>
            </div>
            <div class="template-info mt-2">
              <el-row :gutter="10">
                <el-col :span="24">
                  <div class="text-sm text-gray-600">
                    <span v-if="template.default_route">默认航线: {{ getRouteName(template.default_route) }}</span>
                    <span v-else>默认航线: 未设置</span>
                  </div>
                </el-col>
                <el-col :span="24">
                  <div class="text-sm text-gray-600">
                    <span v-if="template.detection_model">检测模型: {{ getModelName(template.detection_model) }}</span>
                    <span v-else>检测模型: 未设置</span>
                  </div>
                </el-col>
              </el-row>
            </div>
            <div class="template-actions">
              <el-button type="primary" size="small" @click.stop="cloneTemplate(template)" icon="Plus">
                基于模板创建
              </el-button>
            </div>
          </div>
        </el-card>
      </div>
    </el-card>

    <!-- 场景列表 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span>自定义场景列表</span>
        </div>
      </template>
      
      <el-table
        v-loading="loading"
        :data="scenariosData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column prop="id" label="场景ID" width="80" align="center"></el-table-column>
        <el-table-column prop="name" label="场景名称" show-overflow-tooltip></el-table-column>
        <el-table-column prop="description" label="描述" show-overflow-tooltip></el-table-column>
        <el-table-column prop="scenario_type" label="类型" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.scenario_type === 'preset' ? 'info' : 'success'">
              {{ scope.row.scenario_type === 'preset' ? '预设模板' : '自定义场景' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="is_active" label="状态" width="80" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.is_active"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="handleStatusChange(scope.row)"
              :disabled="scope.row.scenario_type === 'preset'"
            />
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" align="center"></el-table-column>
        <el-table-column prop="updated_at" label="更新时间" width="180" align="center"></el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="viewScenarioDetail(scope.row)">
              查看
            </el-button>
            <el-button type="success" size="small" @click="cloneScenario(scope.row)" :disabled="scope.row.scenario_type === 'preset'">
              复制
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)" :disabled="scope.row.scenario_type === 'preset'">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.page_size"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑场景对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="70%"
      @closed="resetDialog"
    >
      <el-form
        ref="scenarioForm"
        :model="scenarioForm"
        :rules="scenarioRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="场景名称" prop="name">
              <el-input v-model="scenarioForm.name" placeholder="请输入场景名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="场景描述" prop="description">
              <el-input
                v-model="scenarioForm.description"
                type="textarea"
                :rows="3"
                placeholder="请输入场景描述"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="适用无人机类型" v-if="currentScenario">
              <el-tag size="small" v-for="(type, index) in processDroneTypes(currentScenario?.drone_type_requirements || [])" :key="index" class="mr-2">
                {{ type }}
              </el-tag>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="检测目标">
              <el-tag
                v-for="(target, index) in processDetectionTargets(scenarioForm.detection_target_ids)"
                :key="index"
                closable
                @close="removeDetectionTarget(target)"
                class="mr-2 mb-2"
              >
                {{ target }}
              </el-tag>
              <el-select
                v-model="newDetectionTarget"
                placeholder="选择检测目标"
                class="mt-2"
                style="width: 200px"
                @change="addDetectionTarget"
                clearable
              >
                <el-option
                  v-for="target in detectionTargets"
                  :key="target.id"
                  :label="target.name"
                  :value="target.id"
                  :disabled="scenarioForm.detection_target_ids.includes(target.id)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="默认航线">
              <el-select
                v-model="scenarioForm.default_route"
                placeholder="选择默认航线"
                clearable
              >
                <el-option
                  v-for="route in flightRoutes"
                  :key="route.id"
                  :label="route.name"
                  :value="route.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="检测模型">
              <el-select
                v-model="scenarioForm.detection_model"
                placeholder="选择检测模型"
                clearable
              >
                <el-option
                  v-for="model in detectionModels"
                  :key="model.id"
                  :label="model.name"
                  :value="model.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 场景详情对话框 -->
    <el-dialog
      title="场景详情"
      v-model="detailDialogVisible"
      width="80%"
    >
      <div v-if="currentScenario" class="scenario-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="场景名称">{{ currentScenario?.name || '' }}</el-descriptions-item>
          <el-descriptions-item label="场景类型">
            <el-tag :type="currentScenario?.scenario_type === 'preset' ? 'info' : 'success'" v-if="currentScenario">
              {{ currentScenario?.scenario_type === 'preset' ? '预设模板' : '自定义场景' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="描述">{{ currentScenario?.description || '' }}</el-descriptions-item>
          <el-descriptions-item label="适用无人机类型" v-if="currentScenario">
            <el-tag size="small" v-for="(type, index) in processDroneTypes(currentScenario?.drone_type_requirements || [])" :key="index" class="mr-2">
              {{ type }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="检测目标">
            <el-tag size="small" v-for="(target, index) in processDetectionTargets(currentScenario.detection_targets || currentScenario.detection_target_objects)" :key="index" class="mr-2">
              {{ target }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="默认航线">
            <el-tag size="small" v-if="currentScenario.default_route">
              {{ getRouteName(currentScenario.default_route) }}
            </el-tag>
            <span v-else>未设置</span>
          </el-descriptions-item>
          <el-descriptions-item label="检测模型">
            <el-tag size="small" v-if="currentScenario.detection_model">
              {{ getModelName(currentScenario.detection_model) }}
            </el-tag>
            <span v-else>未设置</span>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentScenario.created_at }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ currentScenario.updated_at }}</el-descriptions-item>
          <el-descriptions-item v-if="currentScenario.created_from_template_id" label="创建自">
            <el-button type="text" @click="viewTemplateFromDetail">
              {{ currentScenario.created_from_template?.name || '模板已删除' }}
            </el-button>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import { taskScenarioService } from '@/api'
import { detectionTargetService } from '@/api/modules/detectionTarget'

export default {
  name: 'TaskScenarios',
  data() {
    return {
      loading: false,
      dialogVisible: false,
      detailDialogVisible: false,
      dialogTitle: '新建场景',
      editingId: null,
      currentScenario: null,
      presetTemplates: [],
      
      // 航线和检测模型数据
      flightRoutes: [],
      detectionModels: [],
      
      // 搜索表单
      searchForm: {
        name: '',
        scenario_type: '',
        is_active: null
      },
      
      // 分页
      pagination: {
        page: 1,
        page_size: 10,
        total: 0
      },
      
      // 场景表单
      scenarioForm: {
        name: '',
        description: '',
        drone_type_requirements: [],
        detection_target_ids: [],
        default_route: null,
        detection_model: null,
        is_active: true,
        created_from_template_id: null
      },
      
      // 新检测目标
      newDetectionTarget: '',
      
      // 检测目标列表
      detectionTargets: [],
      
      // 表单验证规则
      scenarioRules: {
        name: [
          { required: true, message: '请输入场景名称', trigger: 'blur' },
          { min: 2, max: 50, message: '名称长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入场景描述', trigger: 'blur' }
        ]
      },
      
      // 场景数据
      scenariosData: [],
      
      // 多选数据
      multipleSelection: []
    }
  },
  
  mounted() {
    this.loadPresetTemplates()
    this.loadScenarios()
    this.loadFlightRoutes()
    this.loadDetectionModels()
    this.loadDetectionTargets()
  },
  
  methods: {
    // 加载预设模板
    async loadPresetTemplates() {
      try {
        console.log('正在调用预设模板API...')
        const response = await taskScenarioService.getPresetTemplates()
        console.log('预设模板API响应:', response)
        this.presetTemplates = response || []
        console.log('处理后预设模板数据:', this.presetTemplates)
      } catch (error) {
        ElMessage.error('加载预设模板失败')
        console.error('Failed to load preset templates:', error)
        console.error('预设模板API错误详情:', error.response ? error.response : error)
        this.presetTemplates = []
      }
    },
    
    // 加载场景列表
    async loadScenarios() {
      this.loading = true
      try {
        console.log('正在调用任务场景列表API...')
        const params = {
          ...this.searchForm,
          page: this.pagination.page,
          page_size: this.pagination.page_size
        }
        const response = await taskScenarioService.getTaskScenarios(params)
        console.log('任务场景列表API响应:', response)
        this.scenariosData = response?.items || []
        this.pagination.total = response?.total || 0
        console.log('处理后场景数据:', this.scenariosData)
      } catch (error) {
        ElMessage.error('加载场景列表失败')
        console.error('Failed to load scenarios:', error)
        console.error('场景API错误详情:', error.response ? error.response : error)
        this.scenariosData = []
        this.pagination.total = 0
      } finally {
        this.loading = false
      }
    },
    
    // 搜索
    handleSearch() {
      this.pagination.page = 1
      this.loadScenarios()
    },
    
    // 重置搜索
    resetSearch() {
      this.searchForm.name = ''
      this.searchForm.scenario_type = ''
      this.searchForm.is_active = null
      this.pagination.page = 1
      this.loadScenarios()
    },
    
    // 分页处理
    handleSizeChange(size) {
      this.pagination.page_size = size
      this.loadScenarios()
    },
    
    handleCurrentChange(current) {
      this.pagination.page = current
      this.loadScenarios()
    },
    
    // 显示创建对话框
    showCreateDialog() {
      this.resetDialog()
      this.dialogTitle = '新建场景'
      this.dialogVisible = true
    },
    
    // 重置对话框
    resetDialog() {
      this.editingId = null
      this.scenarioForm.name = ''
      this.scenarioForm.description = ''
      this.scenarioForm.drone_type_requirements = []
      this.scenarioForm.detection_target_ids = []
      this.scenarioForm.default_route = null
      this.scenarioForm.detection_model = null
      this.scenarioForm.is_active = true
      this.scenarioForm.created_from_template_id = null
      this.newDetectionTarget = ''
    },
    
    // 加载检测目标列表
    async loadDetectionTargets() {
      try {
        console.log('正在调用检测目标API...')
        const response = await detectionTargetService.getDetectionTargets()
        console.log('检测目标API响应:', response)
        this.detectionTargets = response.items || []
        console.log('处理后检测目标数据:', this.detectionTargets)
      } catch (error) {
        ElMessage.error('加载检测目标数据失败')
        console.error('Failed to load detection targets:', error)
        console.error('检测目标API错误详情:', error.response ? error.response : error)
        this.detectionTargets = []
      }
    },
    
    // 已移除重复的addDetectionTarget方法定义
    
    // 处理检测目标数据，确保显示友好格式
    processDetectionTargets(targets) {
      if (!targets) return []
      
      // 如果是对象数组，直接返回name属性
      if (Array.isArray(targets) && targets.length > 0 && typeof targets[0] === 'object') {
        return targets.map(target => target.name || '未知目标')
      }
      
      // 如果是ID数组，从检测目标列表中查找对应名称
      if (Array.isArray(targets) && targets.length > 0) {
        return targets.map(targetId => {
          // 确保detectionTargets已加载
          if (!this.detectionTargets || this.detectionTargets.length === 0) {
            return '未知目标'
          }
          
          // 尝试各种ID类型匹配
          const target = this.detectionTargets.find(t => {
            const tId = t.id
            const idToCompare = targetId
            return tId === idToCompare || 
                   String(tId) === String(idToCompare) ||
                   Number(tId) === Number(idToCompare)
          })
          return target ? target.name : '未知目标'
        })
      }
      
      return []
    },
    
    // 处理无人机机型数据
    processDroneTypes(types) {
      if (!Array.isArray(types)) {
        return []
      }
      return types.map(type => {
        if (typeof type === 'object' && type !== null) {
          return type.name || type.type || JSON.stringify(type)
        }
        return type
      })
    },
    
    // 加载航线数据
    async loadFlightRoutes() {
      try {
        // 导入航线服务
        const { flightRouteService } = await import('@/api')
        console.log('正在调用航线API...')
        const response = await flightRouteService.getRoutes()
        console.log('航线API响应:', response)
        this.flightRoutes = response.items || []
        console.log('处理后航线数据:', this.flightRoutes)
      } catch (error) {
        ElMessage.error('加载航线数据失败')
        console.error('Failed to load flight routes:', error)
        console.error('航线API错误详情:', error.response ? error.response : error)
      }
    },
    
    // 加载检测模型数据
    async loadDetectionModels() {
      try {
        // 导入检测模型服务
        const { detectionModelService } = await import('@/api')
        console.log('正在调用检测模型API...')
        const response = await detectionModelService.getDetectionModels()
        console.log('检测模型API响应:', response)
        this.detectionModels = response.items || []
        console.log('处理后检测模型数据:', this.detectionModels)
      } catch (error) {
        ElMessage.error('加载检测模型数据失败')
        console.error('Failed to load detection models:', error)
        console.error('检测模型API错误详情:', error.response ? error.response : error)
      }
    },
    
    // 获取航线名称
    getRouteName(routeId) {
      if (!routeId) return '未设置'
      const route = this.flightRoutes.find(r => r.id === routeId)
      return route ? route.name : '未知航线'
    },
    
    // 获取模型名称
    getModelName(modelId) {
      if (!modelId) return '未设置'
      const model = this.detectionModels.find(m => m.id === modelId)
      return model ? model.name : '未知模型'
    },
    
    // 添加检测目标
    addDetectionTarget(targetId) {
      // 支持通过参数传入或从this.newDetectionTarget获取
      const idToAdd = targetId !== undefined ? targetId : this.newDetectionTarget
      
      if (idToAdd && !this.scenarioForm.detection_target_ids.includes(idToAdd)) {
        this.scenarioForm.detection_target_ids.push(idToAdd)
      }
      // 重置选择器
      this.newDetectionTarget = ''
    },
    
    // 移除检测目标
      removeDetectionTarget(target) {
        // 首先尝试通过名称找到目标对象
        const targetObj = this.detectionTargets.find(t => t.name === target)
        if (targetObj) {
          // 使用多种匹配方式查找ID在数组中的位置
          const index = this.scenarioForm.detection_target_ids.findIndex(id => 
            id === targetObj.id || 
            String(id) === String(targetObj.id) || 
            Number(id) === Number(targetObj.id)
          )
          if (index > -1) {
            this.scenarioForm.detection_target_ids.splice(index, 1)
          }
        } else {
          // 如果找不到目标对象，尝试多种方式匹配ID
          const index = this.scenarioForm.detection_target_ids.findIndex(id => 
            id === target || 
            String(id) === String(target) || 
            Number(id) === Number(target)
          )
          if (index > -1) {
            this.scenarioForm.detection_target_ids.splice(index, 1)
          }
        }
      },
    
    // 提交表单
    async submitForm() {
      try {
        console.log('提交表单数据:', this.scenarioForm)
        console.log('提交URL:', this.editingId ? `task-scenarios/${this.editingId}` : 'task-scenarios')
        
        if (this.editingId) {
          // 更新场景
          await taskScenarioService.updateTaskScenario(this.editingId, this.scenarioForm)
          ElMessage.success('更新成功')
        } else {
          // 创建场景
          await taskScenarioService.createTaskScenario(this.scenarioForm)
          ElMessage.success('创建成功')
        }
        this.dialogVisible = false
        this.loadScenarios()
      } catch (error) {
        ElMessage.error(this.editingId ? '更新失败' : '创建失败')
        console.error('Failed to submit form:', error)
        console.error('错误详情:', error.response ? error.response : error)
      }
    },
    
    // 查看模板详情
    viewTemplateDetail(template) {
      this.currentScenario = template
      this.detailDialogVisible = true
    },
    
    // 查看场景详情
    async viewScenarioDetail(scenario) {
      try {
        const response = await taskScenarioService.getTaskScenario(scenario.id)
        console.log('加载场景详情', response)
        this.currentScenario = response || {}
        this.detailDialogVisible = true
      } catch (error) {
        ElMessage.error('加载场景详情失败')
        console.error('Failed to load scenario detail:', error)
      }
    },
    
    // 从详情中查看模板
    async viewTemplateFromDetail() {
      if (this.currentScenario?.created_from_template_id) {
        try {
          const response = await taskScenarioService.getTaskScenario(this.currentScenario.created_from_template_id)
          console.log('加载模板详情', response)
          this.currentScenario = response || {}
        } catch (error) {
          ElMessage.error('加载模板详情失败')
          console.error('Failed to load template detail:', error)
        }
      }
    },
    
    // 基于模板创建
    cloneTemplate(template) {
      this.resetDialog()
      this.scenarioForm.name = `${template.name}_副本`
      this.scenarioForm.description = template.description
      this.scenarioForm.drone_type_requirements = [...template.drone_type_requirements]
      
      // 转换检测目标为ID数组
      if (template.detection_target_objects && Array.isArray(template.detection_target_objects)) {
        this.scenarioForm.detection_target_ids = template.detection_target_objects.map(target => target.id)
      } else if (template.detection_targets) {
        // 兼容旧格式
        if (Array.isArray(template.detection_targets)) {
          this.scenarioForm.detection_target_ids = template.detection_targets
        }
      }
      
      this.scenarioForm.created_from_template_id = template.id
      this.dialogTitle = '基于模板创建场景'
      this.dialogVisible = true
    },
    
    // 复制场景
    async cloneScenario(scenario) {
      try {
        const response = await taskScenarioService.cloneTaskScenario(scenario.id, {
          name: `${scenario.name}_副本`,
          description: scenario.description
        })
        ElMessage.success('复制成功')
        this.loadScenarios()
      } catch (error) {
        ElMessage.error('复制失败')
        console.error('Failed to clone scenario:', error)
      }
    },
    
    // 切换状态
    async handleStatusChange(scenario) {
      try {
        await taskScenarioService.updateTaskScenario(scenario.id, {
          is_active: scenario.is_active
        })
        ElMessage.success('状态更新成功')
      } catch (error) {
        scenario.is_active = !scenario.is_active // 回滚
        ElMessage.error('状态更新失败')
        console.error('Failed to update status:', error)
      }
    },
    
    // 删除场景
    handleDelete(scenario) {
      ElMessageBox.confirm(
        '确定要删除该场景吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          await taskScenarioService.deleteTaskScenario(scenario.id)
          ElMessage.success('删除成功')
          this.loadScenarios()
        } catch (error) {
          ElMessage.error('删除失败')
          console.error('Failed to delete scenario:', error)
        }
      }).catch(() => {
        // 取消删除
      })
    },
    
    // 多选处理
    handleSelectionChange(val) {
      this.multipleSelection = val
    }
  }
}
</script>

<style scoped>
.task-scenarios-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-filter {
  margin-top: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.template-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.template-card {
  cursor: pointer;
  transition: transform 0.2s;
}

.template-card:hover {
  transform: translateY(-5px);
}

.template-content {
  padding: 10px 0;
}

.template-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 10px;
}

.template-title {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
}

.template-desc {
  margin: 10px 0;
  color: #606266;
  line-height: 1.6;
  height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.template-tags {
  margin: 10px 0;
}

.template-actions {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.scenario-detail {
  max-height: 600px;
  overflow-y: auto;
}
</style>